package admin

import (
	"context"
	"fmt"
	"goProject/db"
	"net/http"

	"gitee.com/ruige_fun/util/ht"
	"gitee.com/ruige_fun/util/std"
	"github.com/kataras/iris/v12"
	"github.com/sashabaranov/go-openai"
)

type pOpenaiSearch struct {
	Keyword string `json:"keyword" validate:"required,min=2"`
}

func openaiSearch(c iris.Context) {
	var p pOpenaiSearch
	err := c.ReadJSON(&p)
	if err != nil {
		c.JSON(std.NewResp(http.StatusBadRequest, "关键词不能低于2个字符", nil, nil))
		return
	}
	key, err := db.RunConfig.Get("OpenAiKey")
	if err != nil || len(key) <= 10 {
		c.JSON(std.NewResp(http.StatusBadRequest, "为设置OpenAiKey，功能暂时不能使用。", nil, nil))
		return
	}
	proxyURL, _ := db.RunConfig.Get("ProxyURL")
	config := openai.DefaultConfig(key)
	proxy, _ := ht.NewProxy(proxyURL)
	config.HTTPClient = &http.Client{Transport: proxy}
	client := openai.NewClientWithConfig(config)
	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: openai.GPT3Dot5Turbo,
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleUser,
					Content: p.Keyword,
				},
			},
		},
	)

	if err != nil {
		c.JSON(std.NewResp(http.StatusBadRequest, fmt.Sprint("出现错误：", err), nil, nil))
		return
	}
	c.JSON(std.NewResp(http.StatusOK, "", resp.Choices[0].Message.Content, nil))
}
